# coding: UTF-8
# Filename : user_api.py
# Company : imedia
# Author : rose
# -*-coding:utf-8 -*-
from api.common.common import *
from api.common import mysql,log,utils,httputils
import time
import user_data_model
import traceback
'''
http://api.imedia.com/app/user/register
'''
#做严格验证
def valitade(cus_id, mobile, pwd, pwd2):
    flag = True
    msg = ''
    if not utils.is_num(mobile) or not len(mobile) == 11 or not utils.regex('^1[3|4|5|8]\d{9}$', mobile): 
        flag = False
        msg += '手机号码不正确'
    if pwd ==None or pwd.strip() == '' or pwd2 == None or pwd2.strip() == '':
        flag = False
        msg += '密码为空或不相等'
    if pwd.strip() != pwd2.strip():
        flag = False
        msg += '两次输入密码不相等'
    if not utils.is_num(cus_id): 
        flag = False
        msg += '用户id不为整数'
    sql = 'select count(id) from `user` where username = %s'
    rst = mysql.get(sql, [mobile])
    if rst[0] != 0:
        flag = False
        msg += '该手机号已存在'
    return (flag, msg)

#获取省份和城市
def get_pro_city(mobile):
    sql = '''
        select province_id, city_id from phone 
        where telstr = %s
    '''
    telstr = mobile[0:7]
    rst = mysql.get(sql,[telstr])
    province_id = 0
    city_id = 0
    if rst != None and len(rst) > 0:
        province_id = rst[0]
        city_id = rst[1]
    return (province_id, city_id)   

#插入user
def insert_into_user(mobile, province_id, city_id, nowtime):
    sql_insert = '''
        insert into `user` 
        (username, reg_time, last_time, province_id, city_id) 
        values (%s, %s, %s, %s, %s) '''
    mobile_int = int(mobile)
    province_id_int = int(province_id)
    city_id_int = int(city_id)
    param_insert = [mobile_int, nowtime, nowtime, province_id_int, city_id_int]
    result = mysql.insert(sql_insert, param_insert)
    return result

#插入user_cus_list
def insert_into_user_cus_list(user_id, cus_id, pwd, now_time):
    sql_insert_ucl = '''
                    insert into user_cus_list
                    (user_id, cus_id, password, reg_time) 
                    values(%s, %s, %s, %s)
                '''
    param_insert_ucl = [user_id, int(cus_id), utils.getMD5(pwd), now_time]
    result = mysql.insert(sql_insert_ucl, param_insert_ucl)
    return result
    
#根据手机号码获取user主键
def get_user_id(mobile):
    mobile_int = int(mobile)
    sql_select = '''select id from `user` where username = %s'''
    user_obj = mysql.get(sql_select, [mobile_int])
    user_id = user_obj[0]    
    return user_id

#注册业务(action 入口)
def register(request):
    httputils.footprint(request)
    #通信验证
    if validate(request):
        return validate(request)
    
    #注册信息验证
    cus_id = httputils.post(request, 'cus_id')
    mobile = httputils.post(request, 'mobile')
    pwd = httputils.post(request, 'pwd')
    pwd2 = httputils.post(request, 'pwd2')
    info = valitade(cus_id, mobile, pwd, pwd2)
    if not info[0]:
        error_info = user_data_model.error_model
        error_info = error_info.replace('{code}', '105')
        error_info = error_info.replace('{msg}', info[1])
        log.print_error_log('warning:user_api.py->method_register验证失败')
        return response(error_info)
    
    
    #----------------------------以下做注册----------------------------
    pro_city = get_pro_city(mobile)
    user_id = 0
    now_time_int = 0
    try:
        #插入user表
        now_time = time.time()
        now_time_int = int(now_time)
        insert_result = insert_into_user(mobile, pro_city[0], pro_city[1], now_time_int)
        
        #查找刚刚主键
        user_id = get_user_id(mobile)
        if insert_result:
            try:
                #插入user_cus_list表
                insert_result_ucl = insert_into_user_cus_list(user_id, cus_id, pwd, now_time_int)
                if insert_result_ucl:
                    success = user_data_model.imedia_body
                    success = success.replace('{uid}', str(user_id))
                    return response(success)
                else:
                    mysql.delete('delete from `user` where id = %s' % user_id)
                    mysql.delete('delete from user_cus_list where user_id = %s' % user_id)
                    error_info = user_data_model.error_model
                    error_info = error_info.replace('{code}', '106')
                    error_info = error_info.replace('{msg}', 'user_cus_list插入失败')
                    log.print_error_log('warning:user_api.py->method_register_user_cus_list插入失败')
                    return response(error_info)
            except:
                mysql.delete('delete from `user` where id = %s' % user_id)
                mysql.delete('delete from user_cus_list where user_id = %s' % user_id)
                log.print_error_log('exception:mysql.py->method_register_user_cus_list_插入异常_'+str(traceback.format_exc()).replace('\n\r',''))
                error_info = user_data_model.error_model
                error_info = error_info.replace('{code}', '106')
                error_info = error_info.replace('{msg}', 'user_cus_list插入异常')
                return response(error_info)
                
        else:
            mysql.delete('delete from `user` where id = %s' % user_id)
            mysql.delete('delete from user_cus_list where user_id = %s' % user_id)
            error_info = user_data_model.error_model
            error_info = error_info.replace('{code}', '106')
            error_info = error_info.replace('{msg}', 'user插入失败')
            log.print_error_log('warning:user_api.py->method_register_user_cus_list插入失败')
            return response(error_info)
    except:
        mysql.delete('delete from `user` where id = %s' % user_id)
        mysql.delete('delete from user_cus_list where user_id = %s' % user_id)
        log.print_error_log('exception:mysql.py->method_register_user_插入异常_'+str(traceback.format_exc()).replace('\n\r',''))
        error_info = user_data_model.error_model
        error_info = error_info.replace('{code}', '106')
        error_info = error_info.replace('{msg}', 'user插入异常')
        return response(error_info)



